﻿using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Newtonsoft.Json;

namespace JSONView {
    public partial class MainForm : Form {
        public MainForm() {
            InitializeComponent();
        }

        private void tsbXmlFormatter_Click(object sender, EventArgs e) {
            this.textBox2.Text = FormatXml(this.textBox1.Text);
        }

        private void tsbJsonFormatter_Click(object sender, EventArgs e) {
            this.textBox2.Text = ConvertJsonString(this.textBox1.Text);
        }

        private string ConvertJsonString(string str) {
            try {
                JsonSerializer serializer = new JsonSerializer();
                TextReader tr = new StringReader(str);
                JsonTextReader jtr = new JsonTextReader(tr);
                object obj = serializer.Deserialize(jtr);
                if(obj != null) {
                    StringWriter textWriter = new StringWriter();
                    JsonTextWriter jsonWriter = new JsonTextWriter(textWriter) {
                        Formatting = Newtonsoft.Json.Formatting.Indented,
                        Indentation = 4,
                        IndentChar = ' '
                    };
                    serializer.Serialize(jsonWriter, obj);
                    return textWriter.ToString();
                } else {
                    return str;
                }
            } catch(Exception ex) {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return string.Empty;
            }
        }

        private static string FormatXml(object xml) {
            try {
                XmlDocument xd;
                if(xml is XmlDocument) {
                    xd = xml as XmlDocument;
                } else {
                    xd = new XmlDocument();
                    xd.LoadXml(xml as string);
                }
                StringBuilder sb = new StringBuilder();
                StringWriter sw = new StringWriter(sb);
                XmlTextWriter xtw = null;
                try {
                    xtw = new XmlTextWriter(sw);
                    xtw.Formatting = System.Xml.Formatting.Indented;
                    xtw.Indentation = 1;
                    xtw.IndentChar = '\t';
                    xd.WriteTo(xtw);
                } catch(Exception ex) {
                    MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                } finally {
                    if(xtw != null)
                        xtw.Close();
                }
                return sb.ToString();
            } catch(Exception exParent) {
                MessageBox.Show(exParent.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return string.Empty;
            }
        }
    }
}
